﻿using System;
using System.Net.Http;
using System.Web.Http.Tracing;
using Common.Logging;
using Newtonsoft.Json;

namespace User.Api.Pipeline.TraceWriters
{
    public class CommonLogTraceWriter : ITraceWriter
    {
        private static readonly ILog Logger =  LogManager.GetLogger(typeof(CommonLogTraceWriter));

        public void Trace(HttpRequestMessage request, string category, TraceLevel level,
           Action<TraceRecord> traceAction)
        {
            var rec = new TraceRecord(request, category, level);
            traceAction(rec);
            WriteTrace(rec);
        }

        protected void WriteTrace(TraceRecord rec)
        {
            var message = string.Format("{0}Category:{1}{0}Exception:{2}{0}Kind:{3}{0}Level" +
                                        ":{4}{0}Message:{5}{0}Operation:{6}{0}Operator:{7}{0}Properties" +
                                        ":{8}{0}Request:{9}{0}RequestId:{10}{0}Status:{11}{0}Timestamp:{12}",
                Environment.NewLine + "          ",
                rec.Category,
                JsonConvert.SerializeObject(rec.Exception, Formatting.None),
                rec.Kind,
                rec.Level,
                rec.Message,
                rec.Operation,
                rec.Operator,
                JsonConvert.SerializeObject(rec.Properties, Formatting.None),
                rec.Request,
                rec.RequestId,
                rec.Status,
                rec.Timestamp);

            if (rec.Level == TraceLevel.Debug)
            {
                Logger.Debug(message);
            }
            else if (rec.Level == TraceLevel.Info)
            {
                Logger.Info(message);
            }
            else if (rec.Level == TraceLevel.Warn)
            {
                Logger.Warn(message);
            }
            else if (rec.Level == TraceLevel.Error)
            {
                Logger.Error(message);
            }
            else if (rec.Level == TraceLevel.Fatal)
            {
                Logger.Fatal(message);
            }
        }
    }
}